using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Common.QR;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;

namespace lwzlz.Application.System
{
    public class FontService
    {
        private readonly IRepository<Font> _repository;

        public FontService()
        {
            _repository = new Repository<Font>();
        }

        #region 查询

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Font Get(int id)
        {
            return _repository.Get(id);
        }

        /// <summary>
        /// 获取输出对象
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public TDto Get<TDto>(int id) where TDto : class, new()
        {
            var entity = Get(id);
            return Mapper.Map<TDto>(entity);
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="dic_conditions"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<FontOutput> GetListPage(
            int pageNumber, int rowsPerPage, Dictionary<string, string> dic_conditions, string field, string order, out int count)
        {
            #region 参数查询

            string where = " WHERE IsDeleted = 0 ";

            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();

            //名称
            if (dic_conditions.ContainsKey("Name"))
            {
                dic.Add("@Name", dic_conditions["Name"]);
                where += " AND Name=@Name ";
            }
            //地址
            if (dic_conditions.ContainsKey("Url"))
            {
                dic.Add("@Url", dic_conditions["Url"]);
                where += " AND Url=@Url ";
            }
            //描述
            if (dic_conditions.ContainsKey("Describe"))
            {
                dic.Add("@Describe", dic_conditions["Describe"]);
                where += " AND Describe=@Describe ";
            }
            //类型
            if (dic_conditions.ContainsKey("Type"))
            {
                dic.Add("@Type", dic_conditions["Type"]);
                where += " AND Type=@Type ";
            }

            #endregion

            #region 排序

            //排序sql语句拼接
            string orderby = " Id DESC ";//默认排序
            if (!string.IsNullOrWhiteSpace(field))
            {
                orderby = string.Format("{0} {1}", field, string.IsNullOrWhiteSpace(order) ? "DESC" : order);
            }

            #endregion

            var list = _repository.GetListPaged(pageNumber, rowsPerPage, where, orderby, dic);

            count = GetListCount(where, dic);

            return Mapper.Map<List<FontOutput>>(list);
        }

        /// <summary>
        /// 获取查询结果行数
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetListCount(string conditions, object param)
        {
            return _repository.RecordCount(conditions, param);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public List<Font> GetList()
        {
            var sql = @"
                SELECT
                        *
                FROM
                        dbo.Ser_Font
                WHERE
                        IsDeleted = 0 ";

            var list = _repository.Query<Font>(sql).ToList();
            return list;
        }

        #endregion

        #region 编辑

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(FontInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                var entity = Mapper.Map<Font>(model);
                entity.CreatorUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.CreationTime = DateTime.Now;

                int? Id = _repository.Insert(entity, dbtran);

                if (Id.HasValue && Id.Value > 0)
                {
                    var strCode = WebConfigurationManager.AppSettings["DomainName"] + "Study/Font/Detail?id=" + HttpUtility.UrlEncode(new Common.Symmetric().Encrypto(Id.Value.ToString()));
                    var date = DateTime.Now;
                    var folder = Path.Combine("upload", "font", date.Year.ToString(), date.Month.ToString());
                    var qrUrl = QRCode.OrdinaryQR(Id.Value, strCode, folder, "");
                    entity.QRCode = qrUrl;
                    entity.Id = Id.Value;
                    _repository.Update(entity, dbtran);
                }

                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int? Update(Font entity, IDbTransaction dbtran)
        {
            return _repository.Update(entity, dbtran);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Edit(FontInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                DateTime now = DateTime.Now;

                var entity = _repository.Get(model.Id, dbtran);
                Mapper.Map(model, entity);//把model数据转移到entity
                entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.LastModificationTime = DateTime.Now;

                _repository.Update(entity, dbtran);
                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void DeleteList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Font model = _repository.Get(Id, dbtran);
                    model.IsDeleted = true;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception)
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        #endregion
    }
}

